<template>
  <section>
    <!--工具条-->

    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <!--<el-form-item>-->
        <!--<el-input v-model="formInline.user" placeholder="姓名"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item>
          <!--<el-button>查询</el-button>-->
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="getRoleGetHttp"></Search>
        </el-form-item>
        <el-form-item>
          <el-button @click="createRole" :disabled="butStatus.add"  type="success">创建</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="updateRole" :disabled="butStatus.update">修改</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="gotopage(211)" :disabled="butStatus.func">功能权限</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" @click="gotopage(212)" :disabled="butStatus.data">数据权限</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="deleteRole" :disabled="butStatus.rm" type="danger">删除 </el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <template>
      <el-table v-loading="listLoading"
                :data="tableData"
                border
                stripe
                style="width: 100%"
                @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column label="角色名称" prop="role_name">
        </el-table-column>
        <el-table-column label="角色类型">
          <template scope="scope">
            {{scope.row.role_type | roleType}}
          </template>
        </el-table-column>
        <el-table-column label="已绑定租户">
          <template scope="scope" class="mytags">
            <el-tag v-if="scope.row.tenant_name" type="primary"
                    v-for="item in (scope.row.tenant_name||'').split(',')" style="margin-right: 5px;">
              {{item}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-for="item in tableTile"
                         :prop="item.key"
                         :label="item.name">
        </el-table-column>
      </el-table>
    </template>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParm.currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageParm.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageParm.count" style="float:right">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="formTitle" size="tiny" v-model="dialogFormVisible" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" :label-width="formLabelWidth">
        <el-form-item label="角色名称" prop="role_name">
          <el-input v-model="form.role_name"
                    :disabled="canRrole"></el-input>
        </el-form-item>
        <!--<el-form-item label="角色类型" prop="role_type">
          <el-select v-model="form.role_type"
                     placeholder="请选择角色类型"
                     :disabled="canRrole"
                     show-message="!dialogFormVisible">
            <el-option
              v-for="item in roleTypeOptions"
              :key="item.role_type_id"
              :label="item.role_type_name"
              :value="item.role_type_id">
            </el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="绑定租户" prop="tenant_ids">
          <el-select v-model="form.tenant_ids" multiple placeholder="请绑定租户">
            <el-option
              v-for="item in tenantOptions"
              :key="item.tenant_id"
              :label="item.tenant_name"
              :value="item.tenant_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="role_desc">
          <el-input v-model="form.role_desc"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

  </section>
</template>
<script>
  import util from '../../common/util'
  import C from '../../common/cfg'
  import dao from '../../common/dao'
  import NProgress from 'nprogress'
  import Search from '../../components/Search.vue'

  export default {
    components: {Search},
    data () {
      var checkRoleName = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('角色名不能为空'));
        }
        if (!/^[A-Za-z]+$/.test(value)) {
          callback(new Error('只能输入大小写英文字母'));
        } else {
          callback();
        }
      };
      var checkRoleDesc = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('角色描述不能为空'));
        }
        setTimeout(() => {
          //if(/[\u4E00-\u9FA5]/g.test(value)){
          if (!/^[A-Za-z]+$/.test(value)) {
            callback(new Error('只能输入大小写英文字母'));
          } else {
            callback();
          }
        }, 1000);
      };
      return {
        rules: {
          role_name: [
            {required: true, message: '请输入角色名', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'},
            {validator: this.validateRoleName, trigger: 'blur'}
          ],
          role_desc: [{
            validator: (rule, value, callback, source, options) => {
              let strlength = value.replace(/[\u4E00-\u9FA5\uF900-\uFA2D]/, '**').length;
              if (strlength > 257) callback(new Error('描述长度不能超过 256 个字符!'));
              else callback()
            }, trigger: 'blur'
          }],
          role_type: [
            {type: 'number', required: true, message: '请选择角色类型', trigger: 'change'}
          ],
        },
        dialogFormVisible: false,
        btnEditText: '提 交',
        formTitle: '新建角色',
        editLoading: false,
        tenantOptions: [],
        roleTypeOptions: [
          {
            role_type_name: '普通角色',
            role_type_id: 0
          },
          {
            role_type_name: '管理员角色',
            role_type_id: 1
          }
        ],
        form: {
          role_id: '',
          role_name: '',
          role_type: 0,
          tenant_ids: [],
          tenant: [],
          role_desc: ''
        },
        canRrole: true,
        tipsClass: '',
        formLabelWidth: '100px',
        editFormRules: {
          role_name: [
            {validator: checkRoleName, trigger: 'blur'}
          ],
          role_desc: [
            {validator: checkRoleDesc, trigger: 'blur'}
          ],
        },
        butStatus: {
          update: true,
          func: true,
          data: true,
          add: false,
          rm: true
        },
        multipleSelection: [],
        formInline: {
          allOpts: [{
            key: 'role_name',
            label: '角色名称',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'role_name',
            label: '角色名称',
            type: '',
            val: ''
          }]
        },
        tableTile: [{
          key: 'user_count',
          name: '用户数量'
        }, {
          key: 'role_desc',
          name: '描述'
        }, {
          key: 'operator_user_name',
          name: '创建者'
        }],
        tableData: [],
        pageParm: {
          'count': 0, //总条数
          'page_size': 20, //每页条数
          'page_count': 0, //总页数
          'currentPage': 1 //当前页数
        }
      }
    },
    methods: {
      getTenantInfoListHttp () {
        let e = {
          'tenant_name': '',
          'start_index': 1,
          'page_count': 99999
        };
        dao.getTenantInfoList(e).then((response) => {
          if (!response.body || response.body.retCode != 200) {
            util.apiMsg(response);
            this.tenantOptions = [];
            return false;
          }
          let pageRes = response.body;
          this.tenantOptions = pageRes.tenant_info_list;
        }, (response) => {
          console.log(response);
        })
      },
      getRoleGetHttp () {
        let e = {
          'role_name': this.formInline.cOpts[0].val,
          'start_index': this.pageParm.currentPage,
          'page_count': this.pageParm.page_size
        };
        dao.getRoleGet(e).then((response) => {
          if (!response.body || response.body.retCode != 200) {
            return false
          }
          let pageRes = response.body;
          this.tableData = pageRes.results;
          if (this.tableData != null && this.tableData.length > 0) {
            this.tableData.map(rowData => {
              let tenantNames = [];
              if (rowData.tenant != null && rowData.tenant.length > 0) {
                rowData.tenant.map(tenant => {
                  tenantNames.push(tenant.tenant_name);
                });
              }
              rowData.tenant_name = tenantNames.toString();
            });
          }
          this.pageParm.count = parseInt(pageRes.count);
        });
      },
      gotopage (p) {
        //获取选中的角色信息
        if (this.multipleSelection.length != 1) {
          this.$message({
            message: '请至少选择一条记录！',
            type: 'warning'
          });
        } else {
          let roleObj = {};
          let rowSelected = this.multipleSelection[0];
          let havePlugins = false;
          this.tableData.map(rowData => {
            if (rowData.role_id === rowSelected.role_id) {
              if (rowData.tenant != null && typeof(rowData.tenant) != 'undefined') {
                rowData.tenant.map(tenant => {
                  if (tenant.tenant_plugins != ''
                    && tenant.tenant_plugins != null
                    && typeof(tenant.tenant_plugins) != 'undefined') {
                    havePlugins = true;
                  }
                });
              }
              roleObj = {
                role_id: rowData.role_id,
                role_name: rowData.role_name,
                tenant: rowData.tenant
              };
            }
          })
          if ((havePlugins && p == '212') || p == '211') {
            util.save('page212_role', roleObj);
            this.$router.push({
              path: `/page${p}`,
            });
          } else {
            this.$message({
              message: '请选择一条具有组件的租户的记录！',
              type: 'warning'
            });
          }

        }
      },
      editSubmit () { 
        //确定创建

        let cs = this.rTest()
        if (cs) { return false }

        this.$refs.form.validate((valid) => {
          if (!valid) return false;
          this.$confirm('确认提交吗？', '提示', {
              type: 'info'
            }).then(() => {
              this.btnEditText = '提交中';
              this.editLoading = true;
              //获取租户信息
              this.form.tenant_ids.map(id => {
                this.form.tenant.push({tenant_id: id, tenant_name: ''});
              });
              let fun = 'addRole';
              if (this.form.role_id != '') {
                 fun = 'updateRole';
              }
              dao[fun](this.form).then((response) => {
                this.btnEditText = '提 交';
                this.editLoading = false;
                this.dialogFormVisible = false;
                if (!response.body || response.body.retCode != 200) {
                  util.apiMsg(response);
                  return false;
                } else {
                  this.$message({
                    type: 'success',
                    message: '提交成功!'
                  });
                  //刷新列表
                  this.getRoleGetHttp();
                }
              });
            })
        })
      },
      handleSizeChange (val) {
        this.pageParm.page_size = val;
        this.getRoleGetHttp();
      },
      handleCurrentChange (val) {
        this.pageParm.currentPage = val;
        this.getRoleGetHttp()
      },
      updateButStatus (val) {
        if (val.length == 1) {
          this.butStatus.update = false;
          this.butStatus.func = false;
          this.butStatus.data = false;
          this.butStatus.rm = false;
        } else if (val.length == 0) {
          this.butStatus.update = true;
          this.butStatus.func = true;
          this.butStatus.data = true;
          this.butStatus.rm = true;
        } else {
          this.butStatus.update = true;
          this.butStatus.func = true;
          this.butStatus.data = true;
          this.butStatus.rm = false;
        }

      },
      handleSelectionChange (val) {
        this.multipleSelection = val;
        this.updateButStatus(val);
      },
      createRole(){

        this.formTitle = '创建角色';
        this.dialogFormVisible = true;
        this.zhHelpTips = '';
        this.canRrole = false;
        this.form = {
          role_id: '',
          role_name: '',
          tenant_ids: [],
          role_type: 0,
          tenant: [],
          role_desc: ''
        }

      },
      rTest () { //解除租户绑定校验

        if (!this.canRrole) { return false }

        let rowData = JSON.parse(JSON.stringify(this.multipleSelection[0]))
        let tenantId = []; //已绑定的租户
        let did = [];
        let status = false
        rowData.tenant.map(item => {
          tenantId.push(item.tenant_id);
        })

        tenantId.map(item => {
          let i = true;
          this.form.tenant_ids.map(nitem => {
            if (item == nitem) { i = false }
          })
          if (i) { did.push(item) }
        })

        did.map(k => {
          rowData.tenant.map(j => {
            if (k == j.tenant_id) {
              if (j.delete_status != 0 && j.delete_status != 2) {
                util.deleteTips(j.tenant_name, j.delete_status)
                status = true
              }
            }
          })
        })
        if (status) { this.form.tenant_ids = tenantId }
        return status

      },
      updateRole () {

        this.formTitle = '修改角色';
        this.dialogFormVisible = true;
        this.canRrole = true;
        let rowData = JSON.parse(JSON.stringify(this.multipleSelection[0]))
        let tenant_id = [];
        let cr = {};
        rowData.tenant.map(item => {
          tenant_id.push(item.tenant_id);
          cr[item.tenant_id] = item.delete_status || 9;
        })
        this.form = {
          role_id: rowData.role_id || '',
          role_name: rowData.role_name || '',
          tenant_ids: tenant_id || [],
          role_type: parseInt(rowData.role_type),
          tenant: [],
          role_desc: rowData.role_desc || ''
        }
        this.zhHelpTips = '';

      },
      deleteRole(){
        let roleIds = [];
        this.multipleSelection.map(rowData => {
          roleIds.push(rowData.role_id);
        });
        if (this.multipleSelection[0].user_count > 0) {
          this.$message({
            message: '请解除关联用户后再删除！',
            type: 'warning'
          });
        } else {
          this.$confirm('确认删除吗？', '提示', {
            type: 'info'
          }).then(() => {
            dao.deleteRole({'role_id': roleIds.toString()}).then((response) => {
              if (!response.body || response.body.retCode != 200) {
                util.apiMsg(response);
                return false;
              } else {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                //刷新列表
                this.getRoleGetHttp();
              }
            });
          });
        }

      },
      validateRoleName (rule, value, callback) { //验证租户是否重复

        if (!value) {
          callback(new Error('请输入角色名称！'))
        } else {
          dao.getValidateRole({
            'role_name': this.form.role_name,
            'role_id': this.form.role_id
          }).then((response) => {
            if (!response.body.result) {
              callback()
            } else {
              callback(new Error('角色名重复!'))
            }
          })
        }
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      }
    },
    mounted () {
      this.getTenantInfoListHttp();
      this.getRoleGetHttp();
    }

  }
</script>

<style scoped>
  .el-dialog .el-select {
    width: 100%;
  }
</style>